class Vplayer {
  constructor(dom, style, option) {
    // 创建 video 对象
    this.video = document.createElement("video");
    // 
    this.dom = dom;
    this.PlaybackState = false;
    // 配置样式
    if (style) {
      this.style = document.createElement('style');
      this.linkStyle('#vplay', style);
    }
    // 设置父级相对定位
    this.dom.style.position = 'relative';
    // 唤起配置选项回调
    if (option) {
      this.option = option;
      this.setParams();
    }
  }
  // 设置样式属性
  linkStyle(className, style) {
    if (!className || !style) {
      return console.log('缺少必须的样式设置参数~');
    }
    let css = '';
    for (let i in style) {
      css += `${i}:${style[i]};`
    }
    if (!this.style) {
      this.style = document.createElement('style');
    }
    if (this.style.type === '') {
      this.style.type = 'text/css';
    }
    this.style.innerHTML += className + '{' + css + '}';
    document.getElementsByTagName('head')[0].appendChild(this.style);
  }
  // 配置参数
  setParams() {
    if (!this.option) {
      return console.error('你没有定义option参数');
    }
    for (let i in this.option) {
      if (i === 'controllers' && this.option[i] === false) {
        break;
      }
      let funParams = this.option[i];
      let firstText = i[0].toUpperCase();
      i = i.replace(/^\w{1}/, firstText);
      if (this['set' + i]) {
        this['set' + i](funParams);
      } else {
        console.error('似乎并没有 ' + i + ' 这项配置...');
      }
    }
  }
  // 控制器
  setControllers(params) {
    this.control = document.createElement("div");
    this.control.className = 'v-control';
    this.dom.appendChild(this.control);
    let domAggregate,videoProgress,videoTime;
    this.domAggregate = domAggregate = {
      videoPlay: null,
      videoProgress: null,
      videoTime: null,
      videoVolume: null
    }
    this.videoProgress = videoProgress = {
      videoProgressBuffer: null,
      videoProgressBufferRange: null,
      sliderProgress: null,
      sliderHandle: null
    }
    this.videoTime = videoTime = {
      videoTimeNow: null,
      videoDivider: null,
      videoTimeTotal: null
    }
    // className 替换
    function replaceText(str) {
      for (let i = 0; i < str.length; i++) {
        if (/[A-Z]/.test(str[i])) {
          str = str.replace(str[i], '-' + str[i].toLowerCase());
        }
      }
      return str;
    }
    // 插入dom节点
    function appendTo(fither, children, domType) {
      for (let i in children) {
        children[i] = document.createElement(domType || 'div');
        children[i].className = replaceText(i);
        fither.appendChild(children[i]);
      }
    }
    let cc = document.createElement('div');
    cc.className = 'player-video-control';
    appendTo(cc, domAggregate);
    appendTo(domAggregate.videoProgress, videoProgress);
    appendTo(domAggregate.videoTime, videoTime, 'span');
    videoTime.videoTimeNow.innerHTML = '00:00';
    videoTime.videoDivider.innerHTML = '/';
    videoTime.videoTimeTotal.innerHTML = '00:00';
    // 控制器上的播放与暂停
    domAggregate.videoPlay.onclick = () => {
      if (this.video.paused) {
        this.play();
      } else {
        this.pause();
      }
    }
    // 控制滑动
    this.progressDrag(this.videoProgress.sliderProgress);
    this.control.appendChild(cc);
    // 点击跳转进度
    this.videoProgress.videoProgressBuffer.onclick =(e) => {
      e = e || event
      e.stopPropagation();
      e.preventDefault();
      this.video.currentTime = (e.offsetX / this.domAggregate.videoProgress.offsetWidth * this.video.duration).toFixed(2);
      console.log((e.offsetX / this.domAggregate.videoProgress.offsetWidth * this.video.duration).toFixed(2))
      if (this.video.paused) {
        this.play();
      }
      return;
    }
  }
  // 封面图
  setCover(src) {
    this.vCover = document.createElement("div");
    this.vCover.className = 'v-cover';
    this.vCoverPlay = document.createElement("div");
    this.vCoverPlay.className = 'v-cover-play';
    this.control.appendChild(this.vCover);
    this.control.appendChild(this.vCoverPlay);
    this.linkStyle('.v-cover', {
      'background-image': 'url(' + src + ')'
    })
    this.vCoverPlay.onclick = () => {
      this.vCover.style.display = 'none';
      this.vCoverPlay.style.display = 'none';
      this.play();
    }
  }
  // 视频路径
  setSrc(arr) {
    if (typeof arr !== 'object' && arr.length) {
      return console.error('option 中 src的值必须为 Array 类型', '传入的值为' + typeof arr);
    }
    arr.forEach((item, index) => {
      let source = document.createElement('source');
      source.src = item;
      this.video.appendChild(source);
    });
    this.video.id = 'vplay';
    this.dom.appendChild(this.video);
    this.video.ondurationchange = () => {
      this.durationchange();
    }
    this.video.oncanplay = () => {
      // 视频可以播放时的回调
      this.canplay();
    }
    this.video.ontimeupdate = () => {
      // 播放进度改变时的回调
      this.timeupdate();
    }
  }
  // 时间变化
  durationchange() {
    this.videoTime.videoTimeTotal.innerHTML = this.dateCalculation(this.video.duration);
  }
  // 时间格式调整
  dateCalculation(date) {
    let dd =Math.floor(date / 60);
    if (dd <= 9) {
      dd = '0' + dd
    }
    let ss = Math.floor(date % 60);
    if (ss <= 9) {
      ss = '0' + ss
    }
    return dd + ':' + ss;
  }
  // 播放时间轴变化
  timeupdate() {
    let currentTime = (this.video.currentTime / this.video.duration) * 100
    this.videoTime.videoTimeNow.innerHTML = this.dateCalculation(this.video.currentTime)
    this.videoProgress.sliderProgress.style.left = currentTime.toFixed(2) + '%';
    this.videoProgress.sliderHandle.style.width = currentTime.toFixed(2) + '%';
  }
  // 进度条拖动
  progressDrag(dom) {
    let _this = this;
    dom.onmousedown = function(ee) {
      ee = ee || event;
      ee.stopPropagation();
      ee.preventDefault();
      let parentWidth = dom.parentNode.offsetWidth;
      let offsetLeft = dom.offsetLeft + 7;
      let xx = ee.pageX - offsetLeft;
      let coordinate;
      window.onmousemove = function(e) {
        e = e || event;
        let x = e.pageX;
        coordinate = ((x - xx) / parentWidth * 100).toFixed(2);
        if (coordinate < 0) {
          _this.videoTime.videoTimeNow.innerHTML = _this.dateCalculation(0)
          return dom.style.left = '0';
        } else if (coordinate > 100) {
          _this.videoTime.videoTimeNow.innerHTML = _this.dateCalculation(_this.video.duration)
          return dom.style.left = '100%';
        }
        _this.videoTime.videoTimeNow.innerHTML = _this.dateCalculation(Number(coordinate) / 100 * _this.video.duration)
        return dom.style.left = coordinate + '%';
      }
      window.onmouseup = function() {
        if (coordinate) {
          _this.video.currentTime = Number(coordinate) / 100 * _this.video.duration;
          _this.play();
        }
        window.onmousemove = null
        window.onmouseup = null
      }
    }
  }
  // 可以开始播放
  canplay() {
    console.log('可以开始播放了！')
  }
  // 播放
  play() {
    console.log('视频开始播放！');
    this.PlaybackState = true;
    if (this.vCoverPlay) {
      this.vCoverPlay.style.display = 'none';
    }
    this.domAggregate.videoPlay.classList.add('stop');
    return this.video.play();
  }
  // 暂停
  pause() {
    console.log('视频已被暂停！')
    this.PlaybackState = false;
    if (this.vCoverPlay) {
      this.vCoverPlay.style.display = 'block';
    }
    this.domAggregate.videoPlay.classList.remove('stop');
    return this.video.pause();
  }
  // 初始化
  init() {
  }
}